<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>在线挂号</title>
    <script src="./js/jquery.min.js"></script>
    <link rel="stylesheet" href="css/registerAppointment.css">
</head>
<body>
<div class="main-wrapper">
    <div class="sidebar">
        <h3>医院病例管理系统</h3>
        <ul>
            <li><a href="./personalInfo.html">个人信息</a></li>
            <li><a href="./myMedicalRecords.html">我的病历</a></li>
            <li><a href="./registerAppointment.html" class="active">在线挂号</a></li>
        </ul>
    </div>
    <div class="main-content">
        <div class="info-card">
            <h2>我的挂号</h2>
            <div class="top-controls">
                <input type="text" class="search-input" id="registerSearchInput" placeholder="搜索医生姓名...">
                <button class="btn btn-success" id="addRegisterBtn">新增挂号</button>
            </div>
            <table>
                <thead>
                <tr>
                    <th>挂号ID</th>
                    <th>医生姓名</th>
                    <th>挂号时间</th>
                    <th>状态</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody id="registerTableBody">
                </tbody>
            </table>
            <div id="registerLoading" class="text-center" style="display: none;">加载中...</div>
            <div id="registerError" class="alert alert-danger" style="display: none;">加载失败</div>
            <nav>
                <ul class="pagination" id="pagination"></ul>
            </nav>
        </div>
    </div>
</div>
<!-- 原生模态框 -->
<div id="registerModal" class="modal-mask" style="display:none;" aria-labelledby="registerModalLabel" aria-hidden="true">
    <div class="modal-box">
        <div class="modal-header">
            <h5 class="modal-title" id="registerModalLabel">挂号</h5>
            <span class="modal-close" id="closeRegisterModalBtn">×</span>
        </div>
        <div class="modal-body">
            <form id="registerForm">
                <input type="hidden" id="registerId">
                <div class="form-group">
                    <label for="doctorSelect" class="form-label">选择医生</label>
                    <select class="form-control" id="doctorSelect" required>
                        <option value="">请选择医生</option>
                    </select>
                </div>
            </form>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-secondary" id="cancelRegisterModalBtn">取消</button>
            <button type="button" class="btn btn-primary" id="saveRegisterBtn">保存</button>
        </div>
    </div>
</div>
<script>
    $(function(){
        let allRegisters = [];
        let currentPage = 1;
        const pageSize = 10;

        // 加载挂号列表
        function loadRegisters() {
            $('#registerLoading').show();
            $('#registerError').hide();
            $.ajax({
                url: 'http://localhost:8080/register/user/list',
                type: 'GET',
                data: { pageNum: currentPage, pageSize: pageSize },
                xhrFields: { withCredentials: true },
                success: function(res) {
                    $('#registerLoading').hide();
                    if (res.code === 0 && res.data) {
                        allRegisters = res.data.records || res.data; // 兼容分页和非分页
                        renderTable(allRegisters);
                        updatePagination(res.data.total || allRegisters.length);
                    } else {
                        $('#registerError').text(res.message || '获取挂号列表失败').show();
                    }
                },
                error: function() {
                    $('#registerLoading').hide();
                    $('#registerError').text('请求失败，请稍后重试').show();
                }
            });
        }

        // 渲染表格
        function renderTable(registers) {
            const $tbody = $('#registerTableBody');
            $tbody.empty();
            if (registers.length === 0) {
                $tbody.append('<tr><td colspan="5" class="text-center">暂无挂号记录</td></tr>');
                return;
            }
            registers.forEach(reg => {
                const $row = $('<tr>');
                $row.append($('<td>').text(reg.id));
                $row.append($('<td>').text(reg.doctorUsername || '-'));
                $row.append($('<td>').text(new Date(reg.registerTime).toLocaleString()));
                $row.append($('<td>').text(reg.status === 0 ? '未就诊' : '已就诊'));
                const $editBtn = $('<button>').addClass('btn btn-sm btn-primary edit-btn').text('编辑').attr('data-id', reg.id);
                const $deleteBtn = $('<button>').addClass('btn btn-sm btn-danger delete-btn').text('删除').attr('data-id', reg.id);
                const $actionsCell = $('<td>');
                $actionsCell.append($editBtn).append($deleteBtn);
                $row.append($actionsCell);
                $tbody.append($row);
            });
        }

        // 分页控件
        function updatePagination(total) {
            const $pagination = $('#pagination');
            $pagination.empty();
            const totalPages = Math.ceil(total / pageSize);
            if (totalPages <= 1) return;
            $pagination.append(createPaginationItem(1, '首页', currentPage === 1));
            $pagination.append(createPaginationItem(currentPage - 1, '上一页', currentPage === 1));
            let startPage = Math.max(1, currentPage - 2);
            let endPage = Math.min(totalPages, currentPage + 2);
            if (startPage > 1) {
                $pagination.append(createPaginationItem(1, 1));
                if (startPage > 2) {
                    $pagination.append($('<li>').addClass('page-item disabled').append($('<span>').addClass('page-link').text('...')));
                }
            }
            for (let i = startPage; i <= endPage; i++) {
                $pagination.append(createPaginationItem(i, i, i === currentPage));
            }
            if (endPage < totalPages) {
                if (endPage < totalPages - 1) {
                    $pagination.append($('<li>').addClass('page-item disabled').append($('<span>').addClass('page-link').text('...')));
                }
                $pagination.append(createPaginationItem(totalPages, totalPages));
            }
            $pagination.append(createPaginationItem(currentPage + 1, '下一页', currentPage === totalPages));
            $pagination.append(createPaginationItem(totalPages, '尾页', currentPage === totalPages));
        }
        function createPaginationItem(page, text, isDisabled = false) {
            const $li = $('<li>').addClass('page-item');
            if (isDisabled) $li.addClass('disabled');
            if (page === currentPage && !isDisabled) $li.addClass('active');
            const $link = $('<a>').addClass('page-link').attr('href', '#').text(text).attr('data-page', page);
            $li.append($link);
            return $li;
        }
        $('#pagination').on('click', '.page-link', function(e){
            e.preventDefault();
            const page = $(this).data('page');
            const $parentLi = $(this).parent('li');
            if ($parentLi.hasClass('disabled') || $parentLi.hasClass('active')) return;
            currentPage = parseInt(page);
            loadRegisters();
        });

        // 搜索功能
        $('#registerSearchInput').on('input', function(){
            const keyword = $(this).val().trim().toLowerCase();
            const filtered = allRegisters.filter(reg =>
                (reg.doctorUsername && reg.doctorUsername.toLowerCase().includes(keyword))
            );
            renderTable(filtered);
        });

        // 加载医生下拉框
        function loadDoctors(selectedId) {
            $.ajax({
                url: 'http://localhost:8080/register/doctor/list',
                type: 'GET',
                xhrFields: { withCredentials: true },
                success: function(res) {
                    if (res.code === 0 && res.data) {
                        const $select = $('#doctorSelect');
                        $select.empty();
                        $select.append('<option value="">请选择医生</option>');
                        res.data.forEach(doc => {
                            $select.append($('<option>').val(doc.id).text(doc.username));
                        });
                        if (selectedId) $select.val(selectedId);
                    }
                }
            });
        }

        // 新增挂号
        $('#addRegisterBtn').click(function(){
            $('#registerId').val('');
            loadDoctors();
            $('#registerModalLabel').text('新增挂号');
            $('#registerModal').show();
        });

        // 编辑挂号
        $('#registerTableBody').on('click', '.edit-btn', function(){
            const id = $(this).data('id');
            $.ajax({
                url: 'http://localhost:8080/register/user/' + id,
                type: 'GET',
                xhrFields: { withCredentials: true },
                success: function(res) {
                    if (res.code === 0 && res.data) {
                        $('#registerId').val(res.data.id);
                        loadDoctors(res.data.doctorId);
                        $('#registerModalLabel').text('编辑挂号');
                        $('#registerModal').show();
                    } else {
                        alert(res.message || '获取挂号信息失败');
                    }
                }
            });
        });

        // 保存挂号
        $('#saveRegisterBtn').click(function(){
            const id = $('#registerId').val();
            const doctorId = $('#doctorSelect').val();
            if (!doctorId) {
                alert('请选择医生');
                return;
            }
            const data = { doctorId: doctorId };
            let url = 'http://localhost:8080/register/user/add', type = 'POST';
            if (id) {
                url = 'http://localhost:8080/register/user/update';
                type = 'POST';
                data.id = id;
            }
            $.ajax({
                url: url,
                type: type,
                contentType: 'application/json',
                data: JSON.stringify(data),
                xhrFields: { withCredentials: true },
                success: function(res) {
                    if (res.code === 0) {
                        $('#registerModal').hide();
                        loadRegisters();
                    } else {
                        alert(res.message || '操作失败');
                    }
                }
            });
        });

        // 删除挂号
        $('#registerTableBody').on('click', '.delete-btn', function(){
            const id = $(this).data('id');
            if (confirm('确定要删除该挂号记录吗？')) {
                $.ajax({
                    url: 'http://localhost:8080/register/user/delete/' + id,
                    type: 'DELETE',
                    xhrFields: { withCredentials: true },
                    success: function(res) {
                        if (res.code === 0) {
                            loadRegisters();
                        } else {
                            alert(res.message || '删除失败');
                        }
                    }
                });
            }
        });

        // 关闭模态框
        $('#closeRegisterModalBtn, #cancelRegisterModalBtn').click(function(){
            $('#registerModal').hide();
        });

        // 页面加载时
        loadRegisters();
    });
</script>
</body>
</html> 